package com.sduept.nwld.dataserver.manager.statistics;

import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.model.countanalyse.CheckPlan;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CheckPlanMaintenanceManager {

	@Autowired
	private SuperDAO dao;

	public List<Integer> getYears(){
		return (List<Integer>) dao.nativeQuery("select distinct year from t_count_protect_check_plan order by year desc");
	}
	
	public List<String> getSubCompany(){
		return (List<String>) dao.nativeQuery("select distinct sub_company  from t_count_protect_check_plan");
	}
	
	public CheckPlan create(CheckPlan checkPlan) {
		return dao.createOrUpdate(checkPlan, CheckPlan.class);
	}
	
	public void deleteCheckPlanById(String id) {
		dao.delete(id, CheckPlan.class);
	}
	/**
	 * 通过年、公司查询除全年总数（month=0）之外的记录
	 */
	public List<CheckPlan> getCheckPlansMonthIsNotEquals0(int year,String subCompany) {
		return dao.findByCondition(CheckPlan.class, "year=? and month!=0 and subCompany=?", year,subCompany);
	}
	
	public List<CheckPlan> getAllCheckPlans() {
		return dao.findAll(CheckPlan.class);
	}
	
	public List<CheckPlan> getCheckPlanById(String id) {
		return dao.findByCondition(CheckPlan.class, "id=?", id);
	}
	
	public List<CheckPlan> query(String year,String month,String subCompany) {
		return queryByCondition(year, month, subCompany);
	}
	
	private List<CheckPlan> queryByCondition(String year,String month,String subCompany) {
		String sql = " 1=1 ";
		List<Object> values = new ArrayList<Object>();
		if(StringUtils.isNotEmpty(year) && !"0".equals(year)) {
			int y = Integer.parseInt(year);
			sql += " and year = ?";
			values.add(y);
		}
		if(StringUtils.isNotEmpty(month) && !"13".equals(month)) {
			int m = Integer.parseInt(month);
			sql += " and month = ?";
			values.add(m);
		}
		if(subCompany != null && !subCompany.equals("全部")) {
			sql += " and subCompany = ?";
			values.add(subCompany);
		}
		List<CheckPlan> ch = dao.findByCondition(CheckPlan.class, sql, values.toArray());
		return ch;
	}

}
